package vip.aster.common.utils;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP地址 工具类
 *
 * @author Aster
 * @since 2023/11/27 17:21
 */
public class IpUtils {

    public static final String UNKNOWN = "unknown";

    /**
     * 获取客户端IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = JakartaServletUtil.getClientIP(request);
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            return getHostIp();
        }
        return getMultistageReverseProxyIp(ip);
    }

    /**
     * 检查是否为内部IP地址
     *
     * @param ip IP地址
     */
    public static boolean internalIp(String ip) {
        if (StrUtil.isBlank(ip) || UNKNOWN.equals(ip)) {
            return true;
        }
        // 判断是否ipv6
        if (Validator.isIpv6(ip)) {
            return false;
        }
        // 检测ipv4是否内部IP
        return NetUtil.isInnerIP(ip);
    }

    /**
     * 获取本地IP地址
     *
     * @return 本地IP地址
     */
    public static String getHostIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ignored) {

        }
        return "127.0.0.1";
    }

    /**
     * 获取主机名
     *
     * @return 本地主机名
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ignored) {

        }
        return "未知";
    }

    /**
     * 从反向代理中，获得第一个非 unknown IP地址
     */
    public static String getMultistageReverseProxyIp(String ip) {
        // 反向代理检测
        if (ip.indexOf(",") > 0) {
            final String[] ips = ip.trim().split(",");
            for (String sub : ips) {
                if (!UNKNOWN.equalsIgnoreCase(sub)) {
                    ip = sub;
                    break;
                }
            }
        }
        return ip;
    }

}
